package com.hzlh.excel;
import java.io.OutputStream;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.WritableWorkbook;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.LocalizedResourceHelper;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.AbstractView;

/**
 * @ClassName: AbstractJxlExcelView 
 * @Description: 重写spring mvc - AbstractJxlExcelView 原因：4.2.0版本该Jxl excel类去除
 * @author liu_wenfeng
 * @date 2014年9月5日 下午4:44:08
 */
public abstract class AbstractJxlExcelView extends AbstractView {
	private String url;

	public AbstractJxlExcelView() {
		setContentType("application/vnd.ms-excel");
	}

	public void setUrl(String url) {
		this.url = url;
	}

	protected boolean generatesDownloadContent() {
		return true;
	}

	protected final void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setContentType(getContentType());
		OutputStream out = response.getOutputStream();
		WritableWorkbook workbook;
		if (this.url != null) {
			Workbook template = getTemplateSource(this.url, request);
			workbook = Workbook.createWorkbook(out, template);
		} else {
			this.logger.debug("Creating Excel Workbook from scratch");
			workbook = Workbook.createWorkbook(out);
		}

		buildExcelDocument(model, workbook, request, response);

		workbook.write();
		out.flush();
		workbook.close();
	}

	protected Workbook getTemplateSource(String url, HttpServletRequest request)
			throws Exception {
		LocalizedResourceHelper helper = new LocalizedResourceHelper(
				getApplicationContext());
		Locale userLocale = RequestContextUtils.getLocale(request);
		Resource inputFile = helper.findLocalizedResource(url, ".xls",
				userLocale);

		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Loading Excel workbook from " + inputFile);
		}
		return Workbook.getWorkbook(inputFile.getInputStream());
	}

	protected abstract void buildExcelDocument(Map<String, Object> paramMap,
			WritableWorkbook paramWritableWorkbook,
			HttpServletRequest paramHttpServletRequest,
			HttpServletResponse paramHttpServletResponse) throws Exception;
}